package com.ocean.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * https://leetcode.cn/problems/3sum/
 */
public class ThreeSum2 {

    public static void main(String[] args) {
        int[] src = new int[]{-1,0,1,2,-1,-4};
        List<List<Integer>> result = new ThreeSum2().threeSum(src);
        System.out.println(result);
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length < 3) {
            return result;
        }
        Arrays.sort(nums);
        for (int first = 0; first < nums.length; first++) {
            if (nums[first] > 0) {
                return result;
            }
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int second = first + 1;
            int third = nums.length - 1;

            while (second < third) {
                int sum = nums[first] + nums[second] + nums[third];
                if (sum == 0) {
                    List<Integer> current = Arrays.asList(nums[first], nums[second], nums[third]);
                    result.add(current);
                    // 跳过相同的
                    while (second < third && nums[second] == nums[second + 1]) {
                        second++;
                    }

                    while (second < third && nums[third] == nums[third - 1]) {
                        third--;
                    }
                    second++;
                    third--;
                } else if (sum > 0) {
                    third--; // 说明要减少3数之和 最大的往前移动
                } else {
                    second++; // 和小了 小的往大那边移动
                }
            }
        }
        return result;
    }
}
